package jgo.plugins.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpServer;

import jgo.JGo;
import jgo.core.ServerPlugin;

public class JavaHttpServerPlugin extends ServerPlugin {

	public JavaHttpServerPlugin(int port) {
		super(port);
	}

	private HttpServer server;



	@Override
	public void start(JGo gin) {
		try {
			server = HttpServer.create(new InetSocketAddress(port), 0);
			server.createContext("/", exchange -> {
				HttpContext context = new HttpContext(exchange);
				gin.handleRequest(context);
				if (!context.responseSent) {
					context.end();
				}
			});
			server.setExecutor(null);
			server.start();
		} catch (IOException e) {
			throw new RuntimeException("Failed to start server", e);
		}
	}

	@Override
	public void stop() {
		if (server != null) {
			server.stop(0);
		}
	}
}